<?php

class DTreeView extends CTreeView {

    //private properties
    private $_tree;
    private $_menus;
    private $_fields_default = array(
        'id' => 'id',
        'text' => 'text',
        'icon' => false,
        'alt' => false,
        'tooltip' => false,
        'id_parent' => 'id_parent',
        'position' => 'position',
    );

    //public properties for the widget
    public $assets;
    public $url;
    public $listChecked = array(0);
    public $isCheckBox = false;
    public $boldCurrent = true;
    public $conditions = array('1=1');
    public $fields;
    public $table;
    public $template = "{icon} {text}";
    public $encode = true;
    public $selectedStyle = "font-weight:bold";
    public $ajaxOptions;
    private static $_listChecked_;
    private static $_isCheckBox_ = false;
    private static $_ajax_;
    private static $_createUrl_ = true;
    //static properties for AJAX
    public static $_assetsPath_;
    public static $_boldCurrent_ = true;
    public static $_template_ = "{icon} {text}";
    public static $_encode_ = true;
    public static $_selectedStyle_ = "font-weight:bold";

    /**
     * Initializes the widget.
     * This method registers all needed client scripts and renders
     * the tree view content.
     */
    public function init() {
        if (isset($this->htmlOptions ['id']))
            $id = $this->htmlOptions ['id'];
        else
            $id=$this->htmlOptions ['id'] = $this->getId();
        if ($this->url !== null)
            $this->url = CHtml::normalizeUrl($this->url);
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript('treeview');
        $options = $this->getClientOptions();
        $options = $options === array() ? '{}' : CJavaScript::encode($options);
        $cs->registerScript('Yii.CTreeView#' . $id, "jQuery(\"#{$id}\").treeview($options);");
        if ($this->cssFile === null)
            $cs->registerCssFile($cs->getCoreScriptUrl() . '/treeview/jquery.treeview.css');
        else if ($this->cssFile !== false)
            $cs->registerCssFile($this->cssFile);
        echo CHtml::tag('ul', $this->htmlOptions, false, false) . "\n";
        if (!isset($this->assets))
            $this->assets = dirname(__FILE__) . '/' . 'assets';
        if ($this->_fields_default['icon'])
            self::$_assetsPath_ = Yii::app()->getAssetManager()->publish($this->assets);
        self::$_template_ = $this->template;
        self::$_listChecked_ = $this->listChecked;
        self::$_isCheckBox_ = $this->isCheckBox;
        self::$_boldCurrent_ = $this->boldCurrent;
        self::$_encode_ = $this->encode;
        self::$_selectedStyle_ = $this->selectedStyle;
        self::$_ajax_ = $this->ajaxOptions;
        echo $this->getData();
        //reset the static properties for the next tree
        self::$_assetsPath_;
        self::$_boldCurrent_ = true;
        self::$_template_ = "{icon} {text}";
        self::$_encode_ = true;
        self::$_createUrl_ = true;
        self::$_selectedStyle_ = "font-weight:bold";
    }

    public function getData() {
        if (!isset($this->_tree)) {
            $refs = array();
            $list = array();

            $this->queryTable();
        }
        echo self::saveDataAsHtml($this->_tree);
    }

    private function queryTable() {
        $fields = $this->getFields();
        $conditions = $this->getConditions();
        $this->_menus = Yii::app()->db->createCommand()
                        ->select($fields)
                        ->from($this->table)
                        ->where($conditions[0], $conditions[1])
                        ->order($this->_fields_default['position'])
                        ->queryAll();
       $this->_tree = $this->getTree($this->_menus);
    }

    private function getFields() {
        $fields = array();
        if (!empty($this->fields)) {
                    $_fields = $this->_fields_default;
                    foreach ($_fields as $field => $val) {
                        if (isset($this->fields[$field])) {
                            $this->_fields_default[$field] = $this->fields[$field];
                            if ($field == 'position')
                                continue;
                            if (is_bool($this->fields[$field])) {
                                if ($this->fields[$field])
                                    $fields[] = $field;
                            }
                            elseif (is_string($this->fields[$field]))
                                $fields[] = $this->fields[$field] . ' AS ' . $field;
                        }
                        elseif ($val) {
                            if ($field == 'position')
                                continue;
                            $fields[] = $field;
                        }
                    }
                  
        }
        else {
                    $fields = $this->_fields_default;
        }
        return implode(', ', $fields);
    }

    private function getTree($menu) {
        foreach ($menu as $data) {
            $thisref = &$refs [$data ['id']];
            $thisref ['id'] = $data ['id'];
            $thisref ['text'] = $this->formatTreeLinks($data ['id'], $data ['text'], $this->url, $this->_fields_default['icon'] ? $data ['icon'] : NULL, $this->_fields_default['tooltip'] ? $data ['tooltip'] : NULL, $this->_fields_default['alt'] ? $data['alt'] : '');

            if ($data ['id_parent'] == 0) {
                $list [$data ['id']] = &$thisref;
            } else {
                $refs [$data ['id_parent']] ['children'] [$data ['id']] = &$thisref;
            }
        }
        return $list;
    }

    private function getConditions() {
        $conditions = array();
        $conditions[] = $this->conditions[0];
        if (isset($this->conditions[1])) {
            $conditions[] = $this->conditions[1];
        }
        else
            $conditions[] = array();
        return $conditions;
    }

    public static function formatTreeLinks($id, $text, $url='', $icon=NULL, $tooltip=NULL, $alt='') {
        $style = '';
        $img = "";
        if ($icon)
            $img = CHtml::image(self::$_assetsPath_ . '/' . $icon, $alt);
        $tmpOptions = $nodeOptions;
        if (strlen($url) && self::$_boldCurrent_)
            if (self::sameUrl($url))
                $style = self::$_selectedStyle_;
        if(!empty($tmpOptions)){
            if(isset($tmpOptions['style']))
                $style = $tmpOptions['style'].';'.$style;
            unset($tmpOptions['style']);
        }
        $htmlOptions = array('title' => $tooltip, 'style' => $style);
        if(!empty($tmpOptions)){
            $htmlOptions = array_merge($htmlOptions,$tmpOptions);
        }
        
        $text = (self::$_encode_) ? CHtml::encode($text) : $text;
        $title = str_replace('{icon}', $img, self::$_template_);
        $title = str_replace('{text}', $text, $title);
        if(self::$_isCheckBox_==true)
        {
                $label = CHtml::checkBox('DCheckBoxList[]', in_array($id, self::$_listChecked_), array('value'=>$id)) . "&nbsp;&nbsp;" . $title;
        }
        else
        {
           $label = CHtml::ajaxLink($title,array($url, 'id'=>$id),self::$_ajax_); 
        } 
        return CHtml::tag('span', $htmlOptions, $label);
    }

    private static function sameUrl($url) {
        if (Yii::app()->request->requestUri == CHtml::normalizeUrl(array($url)))
            return true;
        return false;
    }
}
